package esports

import (
	"github.com/golang-module/carbon/v2"
	"longmen/server/config/global"
	"longmen/server/internal/services/nami/config"
	"longmen/server/internal/services/nami/services"
	"longmen/server/internal/services/nami/utils/restyclient"
	"longmen/server/pkg/common/sdk/tx"
	"longmen/server/pkg/db/mysql/models/models_sports"
	"net/url"
	"strings"
)

type (
	LiveApiResponse struct {
		Code int    `json:"code"`
		Data []Live `json:"data"`
	}

	Live struct {
		SportID     int    `json:"sport_id"`
		MatchID     int    `json:"match_id"`
		MatchTime   int    `json:"match_time"`
		MatchStatus int    `json:"match_status"`
		Comp        string `json:"comp"`
		Home        string `json:"home"`
		Away        string `json:"away"`
		Pushurl1    string `json:"pushurl1"`
		Pushurl2    string `json:"pushurl2"`
		Pushurl3    string `json:"pushurl3"`
	}
)

func (r LiveApiResponse) Interface() []services.InsertLivesInterface {
	a := make([]services.InsertLivesInterface, 0)
	for _, record := range r.Data {
		a = append(a, record)
	}
	global.Log.Info("count : ", len(r.Data))
	return a
}

func getLiveUrl(rtpUrl string, hostType string) string {
	if rtpUrl == "" {
		return ""
	}
	// 纳米的视频地址格式 /sd-id-赛程ID
	steamUrl := getStream(rtpUrl)
	uri := tx.CreateLiveUrl(hostType, steamUrl, 0)
	return uri[0]
}

func getStream(rtpUrl string) string {
	if rtpUrl == "" {
		return ""
	}
	parse, _ := url.Parse(rtpUrl)
	// 纳米的视频地址格式 /live/sd-id-赛程ID
	stream := strings.Replace(parse.Path, "/live/", "", -1)
	return stream
}

func (c Live) Get() models_sports.MatchLives {
	matchLives := models_sports.MatchLives{
		SportID:     c.SportID,
		MatchID:     c.MatchID,
		MatchTime:   c.MatchTime,
		MatchStatus: c.MatchStatus,
		Comp:        c.Comp,
		Home:        c.Home,
		Away:        c.Away,
		UHDLink:     getLiveUrl(c.Pushurl1, tx.HostFLV),
		HDLink:      getLiveUrl(c.Pushurl2, tx.HostFLV),
		SDLink:      getLiveUrl(c.Pushurl3, tx.HostFLV),
		PCLink:      getLiveUrl(c.Pushurl1, tx.HostHLS),
		Category:    models_sports.GetCategory(c.SportID),
		SportName:   models_sports.GetSportName(c.SportID),
	}
	if c.Pushurl2 != "" {
		matchLives.Stream = getStream(c.Pushurl2)
	} else if c.Pushurl3 != "" {
		matchLives.Stream = getStream(c.Pushurl3)
	} else if c.Pushurl1 != "" {
		matchLives.Stream = getStream(c.Pushurl1)
	}
	return matchLives
}

// SyncLiveUrl 电竞比赛直播地址 建议请求频次：1min/次
func SyncLiveUrl() {
	resp := LiveApiResponse{}
	queryStr := config.BuildParamsAndUserAndSecret()
	err := restyclient.GetVideoUrlAndBindRecords(config.VideoLiveUrl+queryStr, &resp)
	if err != nil {
		global.Log.Error("获取赛事直播失败: ", err)
		return
	}
	// 调用入库
	services.CrateOrDeleteLives(resp.Interface())
}

// PlanDelete 计划删除
func PlanDelete() {
	endDay := carbon.Yesterday().EndOfDay().Timestamp()
	services.DeleteByDate(endDay)
}
